package fabuzhe_diyuezhe_model;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * 消息生产者--消息发布者
 * Created by shangjun on 2017/4/3.
 */
public class JMSProducer {
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;//默认的用户名
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认的密码
    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;//默认的连接地址
    private static final int SENDNUM = 10;

    public static void main(String[] args) throws JMSException {
        ConnectionFactory connectionFactory;//连接工厂
        Connection connection = null;//连接
        Session session; //回话，接受或者是发送消息的线程
        Destination destination;//消息的目的地
        MessageProducer messageProducer;//消息的生产者

        //实例化连接工厂
        connectionFactory = new ActiveMQConnectionFactory(JMSProducer.USERNAME, JMSProducer.PASSWORD, JMSProducer.BROKEURL);
        try {
            connection = connectionFactory.createConnection();//通过连接工厂获取连接
            connection.start();
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);//两个参数，第一个是否在session中加入事物,第二个是消息提交的设置
//            destination = session.createQueue("FirstQueue");//创建消息队列
            destination = session.createTopic("firstTopic1");//创建消息的发布者
            messageProducer = session.createProducer(destination);//创建消息生产者
            sendMessage(session, messageProducer);//发送消息
            session.commit();//提交消息！！这很重要，不然就不会再ActiveMQ服务器上显示
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }

    /*
    sendMessage是发送消息的方法
     */
    public static void sendMessage(Session session, MessageProducer messageProducer) throws JMSException {
        for (int i = 0; i < JMSProducer.SENDNUM; i++) {
            TextMessage message = session.createTextMessage("ActiveMQ 发布的消息" + i);
            System.out.println("发布消息" + "ActiveMQ 发布的消息" + i);
            messageProducer.send(message);
        }
    }
}









